package com.wb.utils.encryption

import java.lang.Exception
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.SimpleDateFormat
import java.util.*

class Md5Encryption {

    companion object {
        fun encode(key: String): String {
            try {
                val instance: MessageDigest = MessageDigest.getInstance("MD5")//获取md5加密对象
                val digest: ByteArray = instance.digest(key.toByteArray())//对字符串加密，返回字节数组
                val sb: StringBuffer = StringBuffer()
                for (b in digest) {
                    val i: Int = b.toInt() and 0xff//获取低八位有效值
                    var hexString = Integer.toHexString(i)//将整数转化为16进制
                    if (hexString.length < 2) {
                        hexString = "0" + hexString//如果是一位的话，补0
                    }
                    sb.append(hexString)
                }
                return sb.toString()

            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
            }

            return ""
        }

        private val hexDigits = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")

        fun encodeBymd5(content: String): String {
            try {
                val md5 = MessageDigest.getInstance("MD5")
                val results = md5.digest(content.toByteArray())
                return byteArrayToHexString(results)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ""
        }

        private fun byteArrayToHexString(b: ByteArray): String {
            val resultSb = StringBuffer()
            for (i in b.indices) {
                resultSb.append(byteToHexString(b[i]))
            }
            return resultSb.toString()
        }


        private fun byteToHexString(b: Byte): String {
            var n = b.toInt()
            if (n < 0) n = 256 + n
            val d1 = n / 16
            val d2 = n % 16
            return hexDigits[d1] + hexDigits[d2]
        }

    }

}